pipeline {
  agent any
  environment {
    CI_DOCKER_IMAGE_NAME="${CI_PROJECT_NAME.toLowerCase()}/${GIT_DEPOT_NAME}"
    CI_DOCKER_IMAGE_VERSION="${GIT_LOCAL_BRANCH}-${GIT_COMMIT}"
    CI_K8S_NAMESPACE="${CI_PROJECT_NAME}"
    CI_K8S_DEPLOYMENT_NAME="${GIT_DEPOT_NAME}"
  }
  
  stages  {
    stage("检出") {
      steps {
        checkout(
          [$class: 'GitSCM',
            branches: [[name: GIT_BUILD_REF]],
            userRemoteConfigs: [[
              url: GIT_REPO_URL,
              credentialsId: CREDENTIALS_ID
            ]]
          ]
        )
      }
    }

    stage('安装依赖') {
      steps {
        sh "yarn install"
      }
    }

    stage('代码检测') {
      steps {
        sh "yarn lint"
      }
    }

    stage('代码编译') {
      steps {
        sh "yarn build:${CI_ENV}"
      }
    }

    stage('依赖漏洞扫描') {
     steps {
        npmAuditInDir(directory: '/', collectResult: true)
      }
    }

    stage('构建镜像并推送到制品库') {
      steps {
        sh "docker login ${CI_DOCKER_HOST} -u ${CI_DOCKER_USER} -p ${CI_DOCKER_PASSWORD}"
        sh "docker build -t ${CI_DOCKER_IMAGE_NAME}:${CI_DOCKER_IMAGE_VERSION} -f ${CI_DOCKERFILE_PATH} ${CI_DOCKER_BUILD_CONTEXT}"
        sh "docker push ${CI_DOCKER_IMAGE_NAME}:${CI_DOCKER_IMAGE_VERSION}"
      }
    }

    stage("部署到远端服务") {
      steps {
         sh "kubectl set image deployment -n ${CI_K8S_NAMESPACE} ${CI_K8S_DEPLOYMENT_NAME} ${CI_K8S_DEPLOYMENT_NAME}=${CI_DOCKER_IMAGE_NAME}:${CI_DOCKER_IMAGE_VERSION}"
      }
    }
  }
}